package main

import (
	"bufio"
	"context"
	"flag"
	"log"
	"time"

	"github.com/libp2p/go-libp2p"
	"github.com/libp2p/go-libp2p/core/peer"
)

var (
	targetAddr = flag.String("t", "", "target peer to dial")
)

func init() {
	flag.Parse()
}

func main() {
	host, err := libp2p.New()
	if err != nil {
		log.Panic(err)
	}
	log.Println("Host is", host.ID())

	if *targetAddr != "" {
		ctx := context.Background()
		addrInfo, err := peer.AddrInfoFromString(*targetAddr)
		if err != nil {
			log.Panic(err)
		}
		err = host.Connect(ctx, *addrInfo)
		if err != nil {
			log.Panic(err)
		}
		log.Println("Connected to", addrInfo.ID)

		stream, err := host.NewStream(ctx, addrInfo.ID, "/gitee.com/blinkspark/barry/0.1.0")
		if err != nil {
			log.Panic(err)
		}
		defer stream.Close()
		rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))
		rw.WriteString("Hello, world!\n")
		rw.Flush()

		txt, err := rw.ReadString('\n')
		if err != nil {
			log.Panic(err)
		}
		log.Println(txt)

		_, err = rw.WriteString("_EXIT_\n")
		if err != nil {
			log.Panic(err)
		}
		rw.Flush()
		time.Sleep(time.Second * 1)
	}
}
